package com.letoken.platform.admin.util;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.repo.admin.req.user.QueryLineChartReq;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author wyl
 * @Description TODO
 * @date 2023/4/14 15:16
 * @Version 1.0
 */
public class DateTimeUtil {
    /**
     * 通用折线图时间
     * @param req
     */
    public static List<LocalDate> getLineChartTime(QueryLineChartReq req) {
        LocalDateTime startTime = req.getStartTime();
        LocalDateTime sendTime = req.getSendTime();
        LocalDateTime now = LocalDateTimeUtil.beginOfDay(LocalDateTime.now());
        if (sendTime == null){
            sendTime = now;
        }
        if (startTime == null) {
            //当前时间前第7天
            startTime = LocalDateTimeUtil.offset(sendTime, -7 + 1, ChronoUnit.DAYS);
        }
        startTime = LocalDateTimeUtil.beginOfDay(startTime);
        sendTime = LocalDateTimeUtil.beginOfDay(sendTime);
        long nowToDays = LocalDateTimeUtil.between(now, sendTime).toDays();
        if (nowToDays > 0){
            sendTime = now;
        }

        long days = LocalDateTimeUtil.between(startTime, sendTime).toDays();
        if (days < 0){
            throw new ApiServiceException("结束时间不能小于开始时间！");
        }
        if (days == 0){
            throw new ApiServiceException("开始时间不能等于结束时间！");
        }
        if (days > 30) {
            sendTime = LocalDateTimeUtil.offset(startTime, 30 - 1, ChronoUnit.DAYS);
        }
        req.setStartTime(startTime);
        req.setSendTime(sendTime);
        return getBetweenDate(startTime, sendTime);

    }

    public static List<LocalDate> getBetweenDate(LocalDateTime start,LocalDateTime endTime) {
        List<LocalDate> betweenDateList = new ArrayList<>();
        LocalDate startDate = start.toLocalDate();
        LocalDate endDate = endTime.toLocalDate();
        long distance = ChronoUnit.DAYS.between(startDate, endDate);
        if (distance < 1) {
            return betweenDateList;
        }
        Stream.iterate(startDate, d -> d.plusDays(1)).limit(distance + 1).forEach(betweenDateList::add);
        return betweenDateList;
    }
}

